<template>
  <a-card>
    <template #title>
      <a-button type="primary" @click="addList" v-permiss="['add']">添加</a-button>
    </template>
    <a-table row-key="id" :columns="tableColumn" :pagination="pagination" :data-source="tableData">
      <template #operation="{record}">
        <a-button type="link" @click="editList(record)" v-permiss="['update']">修改</a-button>
      </template>
    </a-table>

    <a-modal v-model:visible="visible.isShow" :title="visible.title" @ok="confirm"
             :afterClose="clearForm"
             width="70%"
             :maskClosable="false">
      <div style="margin-bottom: 10px">
        <a-month-picker style="width:220px" v-model:value="form.month" valueFormat="YYYY-MM" placeholder="请选择月份"
                        format="YYYY-MM"/>
        <div style="margin-top: 15px;display:flex">
          <a-upload
              accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              name="file"
              :showUploadList="false"
              :before-upload="excelFileUpload"
          >
            <a-button type="primary" style="margin-right: 15px">
              <upload-outlined></upload-outlined>
              导入
            </a-button>
          </a-upload>
          <a-button><a href="https://ddhkapps.oss-cn-hongkong.aliyuncs.com/doc/profit_template.xlsx">下载模板</a></a-button>
        </div>
      </div>
      <a-table :columns="addTableColumn" bordered :pagination="false" :data-source="addTableData">
        <template #title="{record}">
          <div v-html="record ?  record.title : ''"></div>
        </template>
        <template #value="{record,index}">
          <a-input style="width:100%" @change="changeValueComputed(index)" v-model:value="form[record.value]"/>
        </template>
      </a-table>
    </a-modal>
  </a-card>
</template>

<script>
import {ref, onMounted, reactive, computed, toRefs, h} from 'vue'
import {importProfit, increaseProfit, fetchProfitList, updateProfit} from '../../../api/finance'
import {
  UploadOutlined
} from '@ant-design/icons-vue'
import {message} from "ant-design-vue";
import XLSX from "xlsx";

const tableColumn = [
  {title: '日期', dataIndex: 'month', width: 150, align: 'center'},
  {title: '更新时间', dataIndex: 'updateTime', width: 150, align: 'center'},
  {title: '操作', width: 100, align: 'center', slots: {customRender: 'operation',}},
]

const addTableData = [
  {title: '一、营业收入', value: 'businessIncome'},
  {title: '减：营业成本', value: 'operatingCost'},
  {title: '税金及附加', value: 'taxesAndSurcharges'},
  {title: '销售费用', value: 'sellingExpenses'},
  {title: '管理费用', value: 'managementExpenses'},
  {title: '财务费用', value: 'financialExpenses'},
  {title: '资产减值损失', value: 'assetsImpairmentLoss'},
  {title: '加：投资收益（损失以“-”号填列）', value: 'incomeFromInvestment'},
  {title: '公允价值变动收益（损失以“-”号填列）', value: 'incomeFromChangesInFairValue'},
  {title: '其他收益', value: 'otherIncome'},
  {
    title: '二、营业利润（亏损以“-”号填列）</br>' +
        '[ = 营业收入-营业成本-税金及附加-营业费用-管理费用-财务费用-资产减值损失+投资收益+公允价值变动收益+其他收益]', value: 'operatingProfit'
  },
  {title: '加：营业外收入', value: 'nonOperatingIncome'},
  {title: '减：营业外支出', value: 'nonOperatingExpenses'},
  {title: '三、利润总额（亏损以“-”号填列）</br> [= 营业利润+营业外收入-营业外支出]', value: 'totalProfit'},
  {title: '减：所得税', value: 'incomeTax'},
  {title: '四、净利润（净亏损以“-”号填列）</br>[ = 利润总额-所得税]', value: 'netProfit'},
  {title: '五、其他综合收益各项目分别扣除所得税影响后的净额', value: 'otherNetProfitNet'},
  {title: '六、综合收益总额 </br>[ = 净利润+其他综合收益各项目分别扣除所得税影响后的净额]', value: 'totalComprehensiveIncome'},
]
const addTableColumn = [
  {
    title: '一级科目名称', dataIndex: 'title', width: 100, align: 'center', slots: {customRender: 'title',}
  },
  {title: '参数', dataIndex: 'value', width: 100, align: 'center', slots: {customRender: 'value',}},
]
export default {
  name: "IncomeManage",
  components: {
    UploadOutlined
  },
  setup() {
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      visible: {
        isShow: false,
        title: '',
        type: ''
      },
      form: {
        month: null
      },

    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total + '条',
      onChange: (page) => {
        state.page.pageNum = page
        getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        getTableData()
      }
    }))

    async function getTableData() {
      const businessId = sessionStorage.getItem('businessValue')
      if (!businessId) return message.error('请选择事业部')
      const res = await fetchProfitList({
        ...state.page,
        businessId: parseInt(businessId)
      })
      if (res.code === 200) {
        const {list, total} = res.data
        state.tableData = list
        state.page.total = total
      }
    }


    function addList() {
      state.visible = {
        isShow: true,
        type: 'add',
        title: '添加'
      }
    }

    function editList(record) {
      state.form = {...record}
      state.visible = {
        isShow: true,
        type: 'update',
        title: '修改'
      }
    }

    function clearForm() {
      state.form = {
        month: null
      }
    }

    function changeValueComputed(index) {
      if (index < 10) {
        setOperatingProfit()
      }
      if (index === 11 || index === 12) {
        setTotalProfit()
      }
      if (index === 13 || index === 14) {
        setNetProfit()
      }
      if (index === 16) {
        setTotalComprehensiveIncome()
      }
    }

    // 设置营业利润
    function setOperatingProfit() {
      const d1 = parseFloat(state.form[addTableData[0].value] || 0)
      const d2 = parseFloat(state.form[addTableData[1].value] || 0)
      const d3 = parseFloat(state.form[addTableData[2].value] || 0)
      const d4 = parseFloat(state.form[addTableData[3].value] || 0)
      const d5 = parseFloat(state.form[addTableData[4].value] || 0)
      const d6 = parseFloat(state.form[addTableData[5].value] || 0)
      const d7 = parseFloat(state.form[addTableData[6].value] || 0)
      const d8 = parseFloat(state.form[addTableData[7].value] || 0)
      const d9 = parseFloat(state.form[addTableData[8].value] || 0)
      const d10 = parseFloat(state.form[addTableData[9].value] || 0)
      const value = (d1 - (d2 + d3 + d4 + d5 + d6 + d7) + (d8 + d9 + d10)).toFixed(2)
      state.form['operatingProfit'] = value
    }

    // 设置利润总额
    function setTotalProfit() {
      const d1 = parseFloat(state.form[addTableData[10].value] || 0)
      const d2 = parseFloat(state.form[addTableData[11].value] || 0)
      const d3 = parseFloat(state.form[addTableData[12].value] || 0)
      const value = (d1 + (d2 - d3)).toFixed(2)
      state.form['totalProfit'] = value
    }

    // 设置净利润
    function setNetProfit() {
      const d1 = parseFloat(state.form[addTableData[13].value] || 0)
      const d2 = parseFloat(state.form[addTableData[14].value] || 0)
      const value = (d1 - d2).toFixed(2)
      state.form['netProfit'] = value
    }

    // 设置综合收益率
    function setTotalComprehensiveIncome() {
      const d1 = parseFloat(state.form[addTableData[15].value] || 0)
      const d2 = parseFloat(state.form[addTableData[16].value] || 0)
      const value = (d1 + d2).toFixed(2)
      state.form['totalComprehensiveIncome'] = value
    }

    async function confirm() {
      if (!state.form.month) {
        return message.error('请选择月份')
      }
      const isAdd = state.visible.type === 'add'
      const api = (params) => isAdd ? increaseProfit(params) : updateProfit(params)
      const res = await api({
        ...state.form,
        businessId: parseInt(sessionStorage.getItem('businessValue'))
      })
      if (res.code === 200) {
        message.success(isAdd ? '添加成功' : '修改成功')
        getTableData()
        state.visible.isShow = false
      }
    }

    function excelFileUpload(file) {
      let reader = new FileReader()
      reader.onload = async (e) => {
        let bstr = e.target.result;
        let wb = XLSX.read(bstr, {type: 'binary', cellDates: true});
        let wsname = wb.SheetNames[0];
        let ws = wb.Sheets[wsname];
        let data = XLSX.utils.sheet_to_json(ws, {header: 1});
        if (data.length > 0) {
          const inputKey = data.filter((item,index)=> index !== 0)
          const keys = {}
          inputKey.forEach((item, index) => {
            keys[addTableData[index].value] = item[1]
          })
          state.form = {
            ...state.form,
            ...keys,
          }
          message.success('导入成功')
        }

      }
      reader.readAsBinaryString(file);
    }

    onMounted(() => {
      getTableData()
    })
    return {
      addTableData,
      excelFileUpload,
      addTableColumn,
      changeValueComputed,
      pagination,
      tableColumn,
      clearForm,
      confirm,
      addList,
      editList,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
